#include "controller/UserRegHandler.h"

#include "ServerContext.h"

#include "DBPool.h"
#include "RedisConnetionPool.h"

#include <time.h>
#include <MD5.h>

#include "RapidJsonMacro.h"

#include "model/UserModel.h"

UserRegHandler::UserRegHandler(const std::string& url):FastCgiHandler(url){

}

UserRegHandler::~UserRegHandler(){

}

void UserRegHandler::doGet(const Fastcgipp::Http::Environment<char>& env,std::basic_ostream<char>& resp) {
    resp << "Content-Type: application/json; charset=utf-8\r\n\r\n";

    resp<<"Hello,TestHandler get!";
}

void UserRegHandler::doPost(const Fastcgipp::Http::Environment<char>& env,std::basic_ostream<char>& resp) {
    resp << "Content-Type: application/json; charset=utf-8\r\n\r\n";

    std::string out;

    auto it = env.posts.find("data");
    if(it == env.posts.cend()) {
        return ;
    }

    std::basic_string<char> data = it->second;

    rapidjson::Document d;
    rapidjson::Value obj(rapidjson::kObjectType);

    d.Parse<0>(data.c_str());
    if(d.HasParseError()){
        RapidJsonObjAddMember(d,obj,"code",-1);
        RapidJsonObjAddMember(d,obj,"msg","json parse error!");

        RapidJsonGetString(obj,out);

        resp<<out;
        return ;
    }

    std::string name = json_check_string(d,"username");
    std::string password = json_check_string(d,"password");
    std::string email = json_check_string(d,"email");
    std::string qq = json_check_string(d,"qq");

    if(name.length() == 0 || password.length() == 0) {
        RapidJsonObjAddMember(d,obj,"code",-1);
        RapidJsonObjAddMember(d,obj,"msg","username or password cannot be empty!");

        RapidJsonGetString(obj,out);

        resp<<out;

        return ;
    }

    std::shared_ptr<User> userPtr(new User());

    userPtr->setusername(name);
    userPtr->setpassword(password);
    userPtr->setemail(email);
    userPtr->setqq(qq);

    std::shared_ptr<UserModel> userModelPtr(new UserModel("dbpool_app","cache_pool"));


    //判断用户是否存在
    if(userModelPtr->userIsExist(userPtr->getusername().c_str())) {

        RapidJsonObjAddMember(d,obj,"code",-1);
        RapidJsonObjAddMember(d,obj,"msg","user name is already exits!");

        RapidJsonGetString(obj,out);

        resp << out;

        return ;
    }

    //新增用户
    if(!userModelPtr->addUser(userPtr.get())){
        RapidJsonObjAddMember(d,obj,"code",-1);
        RapidJsonObjAddMember(d,obj,"msg","data error!");

    }else{
        RapidJsonObjAddMember(d,obj,"code",0);
        RapidJsonObjAddMember(d,obj,"msg","register success!");
    }

    RapidJsonGetString(obj,out);

    resp << out;

    return ;
}
